package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.BindCard;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.Third;
import com.zhiqianbao.entity.UserBank;
import com.zhiqianbao.entity.UserInfo;
import com.zhiqianbao.pay.utils.BaseHelper;
import com.zhiqianbao.pay.utils.EnvConstants;
import com.zhiqianbao.pay.utils.MobileSecurePayer;
import com.zhiqianbao.pay.utils.PayOrder;
import com.zhiqianbao.pay.utils.Rsa;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.LianLianUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

;

/**
 * Created by liang on 2015/12/29.
 */
public class BankCardInfoActivity extends BaseActivity {
    public static final int DATA_FAILD=0x122;
    public static final int CALLBACK=0x123;
    public static final int LIANCONTRACT=0x124;
    private Gson gson = new Gson();
    /**
     * 姓名
     */
    TextView textViewUsername;
    /**
     * 身份证号
     */
    TextView textviewIdCardInfo;
    /**
     * 银行卡号
     */
    TextView textviewBankCard;
    /**
     * 所属银行
     */
    TextView textviewBankInfo;
    /**
     * 预留手机号
     */
    TextView textviewBankPhone;
    /**
     * 信用卡号
     */
    TextView textviewBankCredit;
    /**
     * 所在城市
     */
    TextView textviewBankCity;
    /**
     * 更改银行卡信息按钮
     */
    Button buttonChangeBankCard;
    /**
     * 闪信签约按钮
     */
    Button buttonShanxinSign;
    /**
     * 银行卡闪信认证状态
     */
    TextView contentBankState;
    /**
     * 闪信签约按钮
     */
    RelativeLayout shanxinContent;
    /**
     * 协议选择框
     */
    ImageView imageViewContract;
    boolean protocolCheck = false;
    /**
     * 查看协议按钮
     */
    Button buttonContract;
    private String sign1;
    private String resultO;

    UserInfo userInfo;
    UserBank userBank;

    String reqData;
    private Long userId;
    private String phoneNo;
    private String creditNo;
    private String name;
    private String busi_partner;
    private String no_order;
    private  String dt_order;
    private String name_goods;
    private  String sign_type;
    private  String notify_url;
    private  String valid_order;
    private String shareing_data;
    private  String money_order;
    private String id_no;
    private String oid_partner;
    private  String acct_name;
    private  String no_agree;
    private String user_id;
    private   String total_fee;
    private String term;
    private String cash_fee;
    private  String card_no;
    private SharedPreferanceUtils sharedPreferanceUtils;
    private String risk_item;
    private  String retCode;
    private String sign;
//    @Override
//    protected void onResume() {
//        initView();
//        checkShanxinState();
//        super.onResume();
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bank_card_info);
        init();
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        checkShanxinState();
    }

    private void initData() {
        sharedPreferanceUtils = new SharedPreferanceUtils(this);

    }

    private void lianlianPay() {
          resultO = sharedPreferanceUtils.getResultO();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId",user_id);
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("returnCode",retCode);
                mapParams.put("agreeno",no_agree);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/loan/repay/lianContract/callback",
                        mapParams, BankCardInfoActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILD;
                } else {
                    message.what = CALLBACK;
                    Third data =gson.fromJson(result, Third.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();

    }

    private Handler mHandler = createHandler();

    private Handler createHandler() {
        return new Handler() {
            public void handleMessage(Message msg) {
                String strRet = (String) msg.obj;
                switch (msg.what) {
                    case Constants.RQF_PAY: {
                        Log.i("user_id 3------",user_id);
                        JSONObject objContent = BaseHelper.string2JSON(strRet);
                        Log.i("练练返回",objContent.toString());
                        retCode = objContent.optString("ret_code");
                        String retMsg = objContent.optString("ret_msg");
                         no_agree = objContent.optString("no_agree");
                        Log.i("no_agreeno_agree出来了",no_agree);
                        Log.i("retCodeswww111",retCode);

                        // 成功
                        if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
                            // TODO 卡前置模式返回的银行卡绑定协议号，用来下次支付时使用，此处仅作为示例使用。正式接入时去掉
                           showShortToast1(retMsg);
                            lianlianPay();
//                                BaseHelper.showDialog(BankCardInfoActivity.this, "提示",
//                                        "签约成功，交易状态码：" + retCode+" 返回报文:"+strRet,
//                                        android.R.drawable.ic_dialog_alert);
                                break;

                        } else if (Constants.RET_CODE_PROCESS.equals(retCode)) {
                            // TODO 处理中，掉单的情形
                            showShortToast1(retMsg);
//                            lianlianPay();
                        } else {
                            // TODO 失败
                            showShortToast1(retMsg);
//                            lianlianPay();
                        }
                    }
                    break;
                }
                super.handleMessage(msg);
            }
        };

    }
    private void initView() {
         textViewUsername=(TextView)findViewById(R.id.textView_username);
         textviewIdCardInfo=(TextView)findViewById(R.id.textview_id_card_info);
         textviewBankCard=(TextView)findViewById(R.id.textview_bank_card);
         textviewBankInfo=(TextView)findViewById(R.id.textview_bank_info);
         textviewBankPhone=(TextView)findViewById(R.id.textview_bank_phone);
         textviewBankCredit=(TextView)findViewById(R.id.textview_bank_credit);
         textviewBankCity=(TextView)findViewById(R.id.textview_bank_city);
         buttonChangeBankCard=(Button)findViewById(R.id.button_change_bank_card);
         buttonShanxinSign=(Button)findViewById(R.id.button_shanxin_sign);
         contentBankState=(TextView)findViewById(R.id.content_bank_state);
         shanxinContent=(RelativeLayout)findViewById(R.id.shanxin_content);
         imageViewContract=(ImageView)findViewById(R.id.ImageView_contract);
         buttonContract=(Button)findViewById(R.id.button_contract);
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        try {
            String id = Constants.LOGIN_USER.getId().toString();
//            Log.i("yonghuid"，)
            final List<UserInfo> userInfos = UserInfo.findWithQuery(UserInfo.class, "select * from user_info where user_id = ?", id);
            if (userInfos != null && userInfos.size() > 0) {
                userInfo = userInfos.get(0);
                 name = userInfo.getName();
                String idCard = userInfo.getIdcard();
                userId = userInfo.getUserId();
                sharedPreferanceUtils.setId(String.valueOf(userId));
                sharedPreferanceUtils.setIdCard(idCard);
                sharedPreferanceUtils.setUserName(name);
                //保存用戶id，貸款的時候用
                List<UserBank> userBanks = UserBank.findWithQuery(UserBank.class, "select * from user_bank where user_id = ? ", id);
                if (userBanks != null && userBanks.size() >0) {
                    userBank = userBanks.get(0);
                    String bankCard = userBank.getBankCard();
                    String bankName = userBank.getDeposit();

                    String address = "";
                    if (userBank.getProvince().equals(userBank.getCity())) {
                        address = userBank.getProvince() + userBank.getArea();
                    } else {
                        address = userBank.getProvince() + userBank.getCity() + userBank.getArea();
                    }

                     phoneNo = userBank.getPhoneNo();
                    creditNo = userBank.getCreditNo();

                    textViewUsername.setText(name);
                    textviewIdCardInfo.setText(idCard);
                    textviewBankCard.setText(bankCard);
                    textviewBankInfo.setText(bankName);
                    textviewBankCity.setText(address);
                    textviewBankPhone.setText(phoneNo);
                    textviewBankCredit.setText(creditNo);
                    sharedPreferanceUtils.setBanckCardNuber(bankCard);
                }
            }
        }catch (Exception e){}

        buttonChangeBankCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BankCardInfoActivity.this, UpdateBankActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("userInfo", userInfo);
                bundle.putSerializable("userBank", userBank);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        });

//        buttonChangeBankCard.setOnClickListener(new View.OnClickListener(){
//
//            @Override
//            public void onClick(View v) {
//                PayOrder order = null;
//                //跳转到连连邦卡页面
//                order = constructSignCard();
//                String content4Pay = BaseHelper.toJSONString(order);
//
//                // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持
//
//                MobileSecurePayer msp = new MobileSecurePayer();
//                boolean bRet = msp.paySign(content4Pay, mHandler,
//                        Constants.RQF_PAY, BankCardInfoActivity.this, false);
//            }
//        });

        buttonShanxinSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (protocolCheck) {
                   // getLianLianData();
                            getBindData();
//                    lianlianSign();

                } else {
                    showShortToast1("请阅读并勾选协议");
                }
            }
        });

        //协议勾选按钮
        imageViewContract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (protocolCheck) {
                    protocolCheck = false;
                    imageViewContract.setImageResource(R.drawable.set_off);
                } else {
                    protocolCheck = true;
                    imageViewContract.setImageResource(R.drawable.set_on);
                }

            }
        });

        //查看借款协议
        buttonContract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent contractIntent = new Intent(BankCardInfoActivity.this, DialogContractActivity.class);
                contractIntent.putExtra("url", "/webview/bankProtocol?userId=" + Constants.LOGIN_USER.getId());
                contractIntent.putExtra("title", "米米贷借款协议");
                startActivity(contractIntent);
            }
        });
    }

    private void getBindData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/loan/repay/lianContract",
                        mapParams, BankCardInfoActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILD;
                } else {
                    message.what = LIANCONTRACT;
                    BindCard data =gson.fromJson(result, BindCard.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();

    }

    private PayOrder constructSignCard() {
        PayOrder order = new PayOrder();
//        order.setSign_type(PayOrder.SIGN_TYPE_MD5);
        // RSA 签名方式
         order.setSign_type(sign_type);
        order.setCard_no(card_no);
        order.setBusi_partner(busi_partner);
        order.setNo_order(no_order);
//        order.setDt_order(dt_order);
//        order.setName_goods(name_goods);
//        order.setNotify_url(notify_url);
        order.setMoney_order(money_order);
        order.setId_no(id_no);
//        order.setOid_partner(oid_partner);
        order.setDt_order(dt_order);
        order.setAcct_name(acct_name);
        order.setBusi_partner(busi_partner);
//        order.setNo_agree(no_agree);
        order.setUser_id(String.valueOf(user_id));

        // 风险控制参数
        order.setRisk_item(risk_item);
        order.setOid_partner(oid_partner);
//        order.setOid_partner(oid_partner);
        String content = BaseHelper.sortParamForSignCard(order);
        // MD5 签名方式
//        sign = Md5Algorithm.getInstance().sign(content,
//                sign1);
        // RSA 签名方式
//         sign = Rsa.sign(content,sign1);
//        order.setSign(sign);
        sign = Rsa.sign(content, EnvConstants.RSA_PRIVATE);
        order.setSign(sign);
        return order;
    }

//    private String constructRiskItem() {
//        JSONObject mRiskItem = new JSONObject();
//
//        try {
//            mRiskItem.put("user_info_bind_phone","1");
//            mRiskItem.put("user_info_dt_register", "");
//            mRiskItem.put("frms_ware_category", "4.0");
//            mRiskItem.put("request_imei", "1122111221");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        return mRiskItem.toString();
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 1 :
                UserBank newUserBank = (UserBank) data.getSerializableExtra("userBank");
                textviewBankCard.setText(newUserBank.getBankCard());
                textviewBankInfo.setText(newUserBank.getDeposit());
                String address = "";
                if(newUserBank.getProvince().equals(newUserBank.getCity())) {
                    address = newUserBank.getProvince() + newUserBank.getArea();
                } else {
                    address = newUserBank.getProvince() + newUserBank.getCity() + newUserBank.getArea();
                }
                textviewBankCity.setText(address);
                break;
        }
    }

    /**
     * 检查闪信签约状态
     */
    private void checkShanxinState() {
//        showWaitDialog();
        LianLianUtils.checkLianlianBindCard(BankCardInfoActivity.this, new LianLianUtils.Handler() {
            @Override
            public void process(String result) {
                Message message = new Message();
                message.what = RESULT_OK;
                message.obj = result;
                checkLianLianStateHandler.sendMessage(message);
//                closeWaitDialog();
            }

            @Override
            public void error(final String reason) {
                closeWaitDialog();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(BankCardInfoActivity.this, reason, Toast.LENGTH_SHORT).show();
                        showShortToast1(reason);
                    }
                });

            }
        });
    }
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                Message checkShanxinStateMessage = new Message();
                Map<String, String> param = new HashMap<>();
                param.put("userId", Constants.LOGIN_USER.getId().toString());
                param.put("token",  Constants.LOGIN_USER.getToken());

                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/loan/repay/contract", param, BankCardInfoActivity.this);
                if (StringUtils.isBlank(result)) {
                    checkShanxinStateMessage.what = RESULT_CANCELED;
                } else {
                    Log.i(getClass().getSimpleName(),"result="+result);
                    Result<String> data = Result.fromJson(result, String.class);
                    String state = data.getData();
                    checkShanxinStateMessage.what = RESULT_OK;
                    checkShanxinStateMessage.obj = state;
                }

                getLianLianData.sendMessage(checkShanxinStateMessage);

            }
        }).start();*/

    /**
     * 获取连连签约所需数据
     */
    private void getLianLianData() {
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message checkShanxinStateMessage = new Message();
                Map<String, String> param = new HashMap<>();
                param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                param.put("token",  Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");

                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/loan/repay/contract", param, BankCardInfoActivity.this);
                if (StringUtils.isBlank(result)) {
                    checkShanxinStateMessage.what = RESULT_CANCELED;
                } else {
                    Log.i(getClass().getSimpleName(),"result="+result);
                    Result<String> data = Result.fromJson(result, String.class);
                    String state = data.getData();
                    checkShanxinStateMessage.what = RESULT_OK;
                    checkShanxinStateMessage.obj = state;
                }

                getLianLianData.sendMessage(checkShanxinStateMessage);

            }
        }).start();
    }
    Handler getLianLianData = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == RESULT_OK){
                Object object = msg.obj;
                String data = (String) object;
                setReqData(data);
//                lianlianSign();
            }else{
                showShortToast1("连接超时");
            }
            closeWaitDialog();
        }
    };

    Handler checkLianLianStateHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    Object object = msg.obj;
                    String result = (String) object;
                    //已认证 隐藏认证按钮
                    if (StringUtils.isBlank(result) || LianLianUtils.CARD_STATUS_BIND.equals(result)) {
                        shanxinContent.setVisibility(View.GONE);
                        contentBankState.setText("已认证");
                        //未认证 显示认证按钮
                    } else {
                        shanxinContent.setVisibility(View.VISIBLE);
                        contentBankState.setText("未认证");
                    }
                    break;
            }
            closeWaitDialog();
        }
    };

    private void lianlianSign() {
        PayOrder order = null;
        //跳转到连连邦卡页面
        order = constructSignCard();
        String content4Pay = BaseHelper.toJSONString(order);

        // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持

        MobileSecurePayer msp = new MobileSecurePayer();
        boolean bRet = msp.paySign(content4Pay, mHandler,
                Constants.RQF_PAY, BankCardInfoActivity.this, false);
        Log.i("user_id 2------",user_id);
    }

    public String getReqData() {
        return reqData;
    }

    public void setReqData(String reqData) {
        this.reqData = reqData;
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FAILD:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case CALLBACK:
                    Third response = (Third) msg.obj;
                    if (response!=null){
                        if (response.getCode().equals("0")){
                            showShortToast1(response.getMsg());
                            checkShanxinState();
                        }

                    }
                    break;
                case LIANCONTRACT:
                    BindCard bindCard = (BindCard) msg.obj;
                    if (bindCard!=null){
                        showShortToast1(bindCard.getMsg());
                        if (bindCard.getCode().equals("0")){

                            BindCard.DataBean data = bindCard.getData();

                            if (data !=null){
                                sign_type = data.getSign_type();
                                id_no = data.getId_no();
                                oid_partner = data.getOid_partner();
                                acct_name = data.getAcct_name();
                                card_no = data.getCard_no();
                                oid_partner = data.getOid_partner();
                                sign1 = data.getSign();
                                user_id = data.getUser_id();
                                risk_item = data.getRisk_item();

                                lianlianSign();
                            }

                        }
                    }
                    break;
            }

        }
    };
}
